﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webcar.BLL;
using Webcar.Entitys;
using Webcar.Utils;
using EntityFramework.Extensions;
using System.IO;
using DevExpress.Web.Mvc;
namespace Webcar.Controllers
{
    public partial class MailController : BaseControler
    {
        public ActionResult List()
        {
            return View();
        }
        public ActionResult ListPartialView(string id)
        {
            return PartialView();
        }
        public ActionResult SendList()
        {
            return View();
        }
        public ActionResult SendListPartialView(string id)
        {
            return PartialView();
        }

        public ActionResult Delete(string id)
        {
            using (var DB = new WebcarContext())
            {
                DB.SEND_MSG_HEAD.Delete(a => a.MSG_XH == id);
                DB.SEND_MSG_LOG.Delete(a => a.MSG_XH == id);
                DB.SaveChanges();
            }
            return Success("SendList", "Mail");
        }
        [HttpGet]
        public ActionResult Edit()
        {
            SEND_MSG_HEAD model = new SEND_MSG_HEAD();
            model.SEND_TIME = DateTime.Now;
            model.WRITER = CurrentUser.LoginUserID;
            model.wh = GetNewWH();

            var all_user = from p in WebcarDataProvider.DB.v_all_users
                           join p2 in WebcarDataProvider.DB.sys_dept
                           on p.ori_dept equals p2.deptcode
                           orderby p2.deptcode
                           select new { 
                               account=p.account,
                               name = p.name+"-"+p2.deptname
                           };
            ViewBag.AllUsers = all_user.ToList();
            return View(model: model);
        }

        string GetNewWH()
        {
            string sql = @"select max(SUBSTRING(wh,8,4)) from SEND_MSG_HEAD where wh is not null
                and SUBSTRING(wh,1,6)='" + DateTime.Now.ToString("yyyyMM") + "'";
            var table = WebcarDataProvider.DB.ExecuteDataTable(sql);
            if (table.Rows.Count==0)
            {
                return DateTime.Now.ToString("yyyyMM") + "-0001";
            }
            else
            {
                string ret = table.Rows[0][0].ToString().IsNull("0");
                return DateTime.Now.ToString("yyyyMM") + "-" + (int.Parse(ret) + 1).ToString("0000");
            }
        }
        [HttpPost]
        public ActionResult Edit(SEND_MSG_HEAD model)
        {
            string error = "";
            if (CheckMessageModel(model, ref error) == false)
            {
                ViewBag.ErrorMessage = error;
                return View(model: model);
            }
            string filename = Request.Files.UploadGsFile();
            if(filename.IsNotNull())
                model.filename = filename;//;
            using (var DB = new WebcarContext())
            {
                if (model.MSG_XH.IsNull())
                    model.MSG_XH = "M" + DB.GetSearialId();
                model.WRITER = CurrentUser.LoginUserID;
                model.SEND_TIME = DateTime.Now;
                model.wh = GetNewWH();
                DB.SEND_MSG_HEAD.Add(model);
                //上传人员
                string[] selected_users = CheckBoxListExtension.GetSelectedValues<string>("chkAllUsers");
                if (selected_users.Length == 0)
                {
                    throw new Exception("请选择要发送的用户。");
                }

                foreach (var user in selected_users)
                {
                    SEND_MSG_LOG log = new SEND_MSG_LOG();
                    log.IS_VIEW = "F";
                    log.MAN_CODE = user;
                    log.MSG_XH = model.MSG_XH;
                    DB.SEND_MSG_LOG.Add(log);
                }
                DB.SaveChanges();
            }
            return Success("SendList", "Mail");
        }

        bool CheckMessageModel(SEND_MSG_HEAD model, ref string error)
        {
            if (model.NOTE.IsNull())
            {
                error = "请输入内容。";
                return false;
            }
            return true;
        }



        [HttpGet]
        public ActionResult MailResponse(string id)
        {
            var model = WebcarDataProvider.DB.SEND_MSG_LOG.Find(id, CurrentUser.LoginUserID);
            if (model == null)
            {
                throw new Exception("未找到对应的回复数据。");
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult MailResponse(SEND_MSG_LOG model)
        {
            using (var DB = new WebcarContext())
            {
                var exists = DB.SEND_MSG_LOG.Find(model.MSG_XH, CurrentUser.LoginUserID);
                if (exists == null)
                {
                    throw new Exception("未找到对应的回复数据。");
                }
                exists.RESPONSE_DATE = DateTime.Now;
                exists.RESPONSE_NOTE = model.RESPONSE_NOTE;
                exists.IS_VIEW = "T";
                DB.SaveChanges();
            }
            return RedirectToAction("List");
        }

        public ActionResult ResponseListPartialView(string id)
        {
            var list = from p in WebcarDataProvider.DB.SEND_MSG_LOG
                       join p2 in WebcarDataProvider.DB.v_all_users
                       on p.MAN_CODE equals p2.account
                       into result
                       from bb in result.DefaultIfEmpty()
                       where p.MSG_XH==id
                       select new
                       {
                           user_name = bb.name,
                           response_date = p.RESPONSE_DATE,
                           response_note = p.RESPONSE_NOTE,
                           is_view = p.IS_VIEW=="T"?true:false
                       };

            return PartialView(list.ToList());
        }
    }
}